<?php

namespace app\api\controller;

use app\common\controller\Frontend;
use app\logic\subscribe\SubscribeLogic;
use think\facade\Log;

class Subscribe extends Frontend
{
    public function initialize(): void
    {
        parent::initialize();
    }

    /**
     * 订阅达人
     *
     * @return void
     */
    public function subscribe()
    {
        //TODO 临时操作

        $params = $this->request->param(['user_id']);

        $validate = new \app\api\validate\SubscribeValidate();

        try {
            $validate->scene('subscribe')->check($params);
        } catch (\Throwable $e) {
            $this->error($e->getMessage());
        }

        try {
            SubscribeLogic::getInstance()->subscribe($params, $this->auth->id);
        } catch (\Throwable $e) {
            $this->error(__('Subscription Failed'));
        }

        $this->success(__('Subscription Successful'));
    }

    /**
     * 设置订阅服务的配置
     *
     * 本函数处理订阅服务的相关设置，包括处理请求参数、参数验证、
     * 以及将设置信息保存到数据库中如果操作成功，返回成功信息；
     * 如果操作失败或参数验证失败，则返回相应的错误信息
     */
    public function settings()
    {
        // 获取请求参数，包括年费、季度费、月费、是否促销、折扣率和促销文本
        $params = $this->request->param(['yearly', 'quarterly', 'monthly', 'is_on_sale', 'discount', 'promotion_text']);

        // 实例化订阅验证器，用于验证请求参数的合法性
        $validate = new \app\api\validate\SubscribeValidate();

        // 尝试对参数进行验证，如果验证失败，则抛出异常，并返回验证失败的信息
        try {
            $validate->scene('settings')->check($params);
        } catch (\Throwable $e) {
            $this->error($e->getMessage());
        }

        // 尝试将设置信息保存到数据库中如果操作失败，则抛出异常，
        // 并根据当前环境返回不同的错误信息
        try {
            SubscribeLogic::getInstance()->setSettings($params, $this->auth->id);
        } catch (\Throwable $e) {
            $message = config('app.env') != 'prod' ? $e->getMessage() : __('Settings Failed');
            $this->error($message);
        }

        // 如果操作成功，返回成功信息
        $this->success(__('Settings Successful'));
    }

    /**
     * 获取用户设置
     *
     */
    public function getSettings()
    {
        try {
            // 尝试从订阅逻辑中获取当前用户的设置信息
            $data = SubscribeLogic::getInstance()->getSetting($this->auth->id);
        } catch (\Throwable $e) {
            // 根据环境配置，决定是否显示详细异常信息
            $message = config('app.env') != 'prod' ? $e->getMessage() : __('server error');
            // 记录错误信息
            $this->error($message);
        }

        // 返回成功信息及用户设置数据
        $this->success(__('success'), $data);
    }


    /**
     * 检查订阅设置
     */
    public function checkSettings()
    {
        // 调用SubscribeLogic单例的checkSettings方法检查设置，传入当前用户ID
        $status = SubscribeLogic::getInstance()->checkSettings($this->auth->id);

        // 返回成功消息和订阅设置的状态
        $this->success(__('success'), ['status'=>$status]);
    }


    /**
     * 我的订阅
     */
    public function mySubscribe()
    {
        $limit = (int)$this->request->param('size');
        if ($limit > 15 || $limit < 0) {
            $limit = 15;
        }

        //检查当前登录者是否是达人
        if (!$this->auth->isCreator()) {
            $this->error(__('403 Forbidden'), null, 403, null, ['statusCode' => 403]);
        }

        try {
            $result = SubscribeLogic::getInstance()->mySubscribe($this->auth->id, $limit);
        }catch (\Throwable $exception) {
            $message = config('app.env') != 'prod' ? $exception->getMessage().PHP_EOL . $exception->getTraceAsString() : __('server error');
            Log::channel('my')->error($exception->getMessage() . PHP_EOL . $exception->getTraceAsString());
            $this->error($message);
        }

        $this->success(__('success'), $result);
    }

    /**
     * 订阅我的
     */
    public function subscribeMe()
    {
        $limit = (int)$this->request->param('size');
        if ($limit > 15 || $limit < 0) {
            $limit = 15;
        }

        //检查当前登录者是否是达人
        if (!$this->auth->isCreator()) {
            $this->error(__('403 Forbidden'), null, 403, null, ['statusCode' => 403]);
        }

        try {
            $result = SubscribeLogic::getInstance()->subscribeMe($this->auth->id, $limit);
        }catch (\Throwable $exception) {
            $message = config('app.env') != 'prod' ? $exception->getMessage().PHP_EOL . $exception->getTraceAsString() : __('server error');
            Log::channel('my')->error($exception->getMessage() . PHP_EOL . $exception->getTraceAsString());
            $this->error($message);
        }

        $this->success(__('success'), $result);
    }
}